import { resultFailure, resultSuccess } from '@utils/resultFormatter'
import { prisma } from '../index.repo'

/**
 * ==================== EventMember 管理 ====================
 * 管理事件和成员之间的关联关系
 */

/**
 * 将成员添加到事件
 * @param eventId 事件ID
 * @param memberIds 成员ID列表
 */
export const addMembersToEvent = async (eventId: string, memberIds: string[]) => {
    try {
        const result = await prisma.eventMember.createMany({
            data: memberIds.map(memberId => ({
                eventId,
                memberId
            })),
            skipDuplicates: true
        })

        return resultSuccess(true, 201, result, `${result.count} members added to event successfully`)
    } catch (err) {
        return resultFailure(false, 500, String(err))
    }
}

/**
 * 从事件中移除成员
 * @param eventId 事件ID
 * @param memberIds 成员ID列表
 */
export const removeMembersFromEvent = async (eventId: string, memberIds: string[]) => {
    try {
        const result = await prisma.eventMember.updateMany({
            where: {
                eventId,
                memberId: { in: memberIds }
            },
            data: {
                deletedAt: new Date()
            }
        })

        return resultSuccess(true, 200, result, `${result.count} members removed from event successfully`)
    } catch (err) {
        return resultFailure(false, 500, String(err))
    }
}

/**
 * 读取事件的所有成员
 * @param eventId 事件ID
 * @param offset 偏移量
 * @param limit 限制数量
 */
export const readEventMembers = async (eventId: string, offset: number = 0, limit: number = 10) => {
    try {
        const total = await prisma.eventMember.count({
            where: { eventId, deletedAt: null }
        })

        const result = await prisma.eventMember.findMany({
            where: { eventId, deletedAt: null },
            skip: offset,
            take: limit,
            include: {
                member: {
                    select: {
                        id: true,
                        identifier: true,
                        realName: true,
                        nickName: true,
                        wxOpenId: true
                    }
                }
            }
        })

        return resultSuccess(true, 200, { total, result })
    } catch (err) {
        return resultFailure(false, 500, String(err))
    }
}

/**
 * 读取成员参与的所有事件
 * @param memberId 成员ID
 * @param offset 偏移量
 * @param limit 限制数量
 */
export const readMemberEvents = async (memberId: string, offset: number = 0, limit: number = 10) => {
    try {
        const total = await prisma.eventMember.count({
            where: { memberId, deletedAt: null }
        })

        const result = await prisma.eventMember.findMany({
            where: { memberId, deletedAt: null },
            skip: offset,
            take: limit,
            include: {
                event: {
                    select: {
                        id: true,
                        title: true,
                        description: true,
                        startAt: true,
                        endAt: true,
                        status: true
                    }
                }
            }
        })

        return resultSuccess(true, 200, { total, result })
    } catch (err) {
        return resultFailure(false, 500, String(err))
    }
}

/**
 * ==================== EventGroup 管理 ====================
 * 管理事件和组之间的关联关系
 */

/**
 * 将组添加到事件
 * @param eventId 事件ID
 * @param groupIds 组ID列表
 */
export const addGroupsToEvent = async (eventId: string, groupIds: string[]) => {
    try {
        const result = await prisma.eventGroup.createMany({
            data: groupIds.map(groupId => ({
                eventId,
                groupId
            })),
            skipDuplicates: true
        })

        return resultSuccess(true, 201, result, `${result.count} groups added to event successfully`)
    } catch (err) {
        return resultFailure(false, 500, String(err))
    }
}

/**
 * 从事件中移除组
 * @param eventId 事件ID
 * @param groupIds 组ID列表
 */
export const removeGroupsFromEvent = async (eventId: string, groupIds: string[]) => {
    try {
        const result = await prisma.eventGroup.updateMany({
            where: {
                eventId,
                groupId: { in: groupIds }
            },
            data: {
                deletedAt: new Date()
            }
        })

        return resultSuccess(true, 200, result, `${result.count} groups removed from event successfully`)
    } catch (err) {
        return resultFailure(false, 500, String(err))
    }
}

/**
 * 读取事件的所有组
 * @param eventId 事件ID
 * @param offset 偏移量
 * @param limit 限制数量
 */
export const readEventGroups = async (eventId: string, offset: number = 0, limit: number = 10) => {
    try {
        const total = await prisma.eventGroup.count({
            where: { eventId, deletedAt: null }
        })

        const result = await prisma.eventGroup.findMany({
            where: { eventId, deletedAt: null },
            skip: offset,
            take: limit,
            include: {
                group: {
                    select: {
                        id: true,
                        name: true,
                        organizationId: true
                    }
                }
            }
        })

        return resultSuccess(true, 200, { total, result })
    } catch (err) {
        return resultFailure(false, 500, String(err))
    }
}

/**
 * 读取组参与的所有事件
 * @param groupId 组ID
 * @param offset 偏移量
 * @param limit 限制数量
 */
export const readGroupEvents = async (groupId: string, offset: number = 0, limit: number = 10) => {
    try {
        const total = await prisma.eventGroup.count({
            where: { groupId, deletedAt: null }
        })

        const result = await prisma.eventGroup.findMany({
            where: { groupId, deletedAt: null },
            skip: offset,
            take: limit,
            include: {
                event: {
                    select: {
                        id: true,
                        title: true,
                        description: true,
                        startAt: true,
                        endAt: true,
                        status: true
                    }
                }
            }
        })

        return resultSuccess(true, 200, { total, result })
    } catch (err) {
        return resultFailure(false, 500, String(err))
    }
}

/**
 * ==================== EventCombinationGroup 管理 ====================
 * 管理事件组合和组之间的关联关系
 */

/**
 * 将组添加到事件组合
 * @param eventCombinationId 事件组合ID
 * @param groupIds 组ID列表
 */
export const addGroupsToEventCombination = async (eventCombinationId: string, groupIds: string[]) => {
    try {
        const result = await prisma.eventCombinationGroup.createMany({
            data: groupIds.map(groupId => ({
                eventCombinationId,
                groupId
            })),
            skipDuplicates: true
        })

        return resultSuccess(true, 201, result, `${result.count} groups added to event combination successfully`)
    } catch (err) {
        return resultFailure(false, 500, String(err))
    }
}

/**
 * 从事件组合中移除组
 * @param eventCombinationId 事件组合ID
 * @param groupIds 组ID列表
 */
export const removeGroupsFromEventCombination = async (eventCombinationId: string, groupIds: string[]) => {
    try {
        const result = await prisma.eventCombinationGroup.updateMany({
            where: {
                eventCombinationId,
                groupId: { in: groupIds }
            },
            data: {
                deletedAt: new Date()
            }
        })

        return resultSuccess(true, 200, result, `${result.count} groups removed from event combination successfully`)
    } catch (err) {
        return resultFailure(false, 500, String(err))
    }
}

/**
 * 读取事件组合的所有组
 * @param eventCombinationId 事件组合ID
 * @param offset 偏移量
 * @param limit 限制数量
 */
export const readEventCombinationGroups = async (
    eventCombinationId: string,
    offset: number = 0,
    limit: number = 10
) => {
    try {
        const total = await prisma.eventCombinationGroup.count({
            where: { eventCombinationId, deletedAt: null }
        })

        const result = await prisma.eventCombinationGroup.findMany({
            where: { eventCombinationId, deletedAt: null },
            skip: offset,
            take: limit,
            include: {
                group: {
                    select: {
                        id: true,
                        name: true,
                        organizationId: true
                    }
                }
            }
        })

        return resultSuccess(true, 200, { total, result })
    } catch (err) {
        return resultFailure(false, 500, String(err))
    }
}

/**
 * 读取组关联的所有事件组合
 * @param groupId 组ID
 * @param offset 偏移量
 * @param limit 限制数量
 */
export const readGroupEventCombinations = async (groupId: string, offset: number = 0, limit: number = 10) => {
    try {
        const total = await prisma.eventCombinationGroup.count({
            where: { groupId, deletedAt: null }
        })

        const result = await prisma.eventCombinationGroup.findMany({
            where: { groupId, deletedAt: null },
            skip: offset,
            take: limit,
            include: {
                eventCombination: {
                    select: {
                        id: true,
                        name: true,
                        description: true,
                        organizationId: true
                    }
                }
            }
        })

        return resultSuccess(true, 200, { total, result })
    } catch (err) {
        return resultFailure(false, 500, String(err))
    }
}

/**
 * ==================== 批量操作 ====================
 */

/**
 * 同步事件的成员列表（删除旧的，添加新的）
 * @param eventId 事件ID
 * @param memberIds 新的成员ID列表
 */
export const syncEventMembers = async (eventId: string, memberIds: string[]) => {
    try {
        const result = await prisma.$transaction(async tx => {
            // 软删除所有现有的成员关联
            await tx.eventMember.updateMany({
                where: { eventId },
                data: { deletedAt: new Date() }
            })

            // 添加新的成员关联
            const created = await tx.eventMember.createMany({
                data: memberIds.map(memberId => ({
                    eventId,
                    memberId
                })),
                skipDuplicates: true
            })

            return created
        })

        return resultSuccess(true, 200, result, `Event members synchronized successfully`)
    } catch (err) {
        return resultFailure(false, 500, String(err))
    }
}

/**
 * 同步事件的组列表（删除旧的，添加新的）
 * @param eventId 事件ID
 * @param groupIds 新的组ID列表
 */
export const syncEventGroups = async (eventId: string, groupIds: string[]) => {
    try {
        const result = await prisma.$transaction(async tx => {
            // 软删除所有现有的组关联
            await tx.eventGroup.updateMany({
                where: { eventId },
                data: { deletedAt: new Date() }
            })

            // 添加新的组关联
            const created = await tx.eventGroup.createMany({
                data: groupIds.map(groupId => ({
                    eventId,
                    groupId
                })),
                skipDuplicates: true
            })

            return created
        })

        return resultSuccess(true, 200, result, `Event groups synchronized successfully`)
    } catch (err) {
        return resultFailure(false, 500, String(err))
    }
}

/**
 * 同步事件组合的组列表（删除旧的，添加新的）
 * @param eventCombinationId 事件组合ID
 * @param groupIds 新的组ID列表
 */
export const syncEventCombinationGroups = async (eventCombinationId: string, groupIds: string[]) => {
    try {
        const result = await prisma.$transaction(async tx => {
            // 软删除所有现有的组关联
            await tx.eventCombinationGroup.updateMany({
                where: { eventCombinationId },
                data: { deletedAt: new Date() }
            })

            // 添加新的组关联
            const created = await tx.eventCombinationGroup.createMany({
                data: groupIds.map(groupId => ({
                    eventCombinationId,
                    groupId
                })),
                skipDuplicates: true
            })

            return created
        })

        return resultSuccess(true, 200, result, `Event combination groups synchronized successfully`)
    } catch (err) {
        return resultFailure(false, 500, String(err))
    }
}
